package com.dgut.Utils;

import com.dgut.model.UserInfo;
import com.dgut.service.UserService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * @author GooRay
 * 创建于 2020/6/21
 */
@Component
public class EXCELUtils {

    private static EXCELUtils excelUtils;

    @Autowired
    private UserService userService;

    @PostConstruct
    public void init(){
        excelUtils = this;
        userService = this.userService;
    }

    public static String DownLoad() throws IOException {
        return new EXCELUtils().createExcel();
    }

    public String createExcel() throws IOException {
        String[] title = {"住户","身份证","栋号","房号","最新出入时间","最新温度"};
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
        HSSFSheet sheet = hssfWorkbook.createSheet();
        int rows =0;
        HSSFRow row;
        row = sheet.createRow(rows++);//第一行
        HSSFCell cell;
        for (int i = 0; i < title.length; i++) {    //6列
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
        }
        List<UserInfo> userInfos = excelUtils.userService.findAllMessage();
        for (UserInfo userInfo : userInfos) {
            int col = 0;
            row = sheet.createRow(rows++);
            cell = row.createCell(col++);
            cell.setCellValue(userInfo.getUser_name());
            cell = row.createCell(col++);
            cell.setCellValue(userInfo.getUser_id_card());
            cell = row.createCell(col++);
            cell.setCellValue(userInfo.getBuilding());
            cell = row.createCell(col++);
            cell.setCellValue(userInfo.getRoom_number());
            cell = row.createCell(col++);
            cell.setCellValue(userInfo.getLastest_time().toString());
            cell = row.createCell(col++);
            cell.setCellValue(userInfo.getLastest_temp());
        }
        File file = new File("demo.xls");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        hssfWorkbook.write(fileOutputStream);
        fileOutputStream.close();
        return file.getName();
    }
}
